<template>
  <commonDrawer
    :title="type==='edit'?'修改时间条件':'新增时间条件'"
    size="42%"
    :drawer="drawer"
    @closeDraw="openOrCloseDrawer"
    @cancelFun="drawer=false"
    @save="save">
    <template slot="column">
      <el-form class="m7-form" :model="form" :rules="rules" ref="formRef" label-position="top" size="mini">
        <el-form-item label="时间条件" prop="name">
          <el-input size="mini" type="text" v-model.trim="form.name" placeholder="请输入时间条件"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input size="mini" type="textarea" v-model.trim="form.description"  placeholder="请输入说明" autosize></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio v-model="form.type" label="cycle">周期时间条件</el-radio>
          <el-radio v-model="form.type" label="stable">固定时间条件</el-radio>
        </el-form-item>
        <el-form-item label="时段" v-if="form.type === 'cycle'">
          <div class="time-step-box" v-for="(item, index) in form.cyclePeriods" :key="index">
            <div class="dashed-box">
              <el-checkbox-group v-model="item.days" @change="changeDays(index, item.days)">
                <!--item.days.indexOf(dayItem.value) < 0 && currentDisabled.indexOf(dayItem.value) < 0 当前没有选中&&可勾选的里面没有当前项-->
                <el-checkbox v-for="dayItem in dayList" :label="dayItem.value" :key="dayItem.lable" :disabled="item.days.indexOf(dayItem.value) < 0 && currentDisabled.indexOf(dayItem.value) < 0 ? true: false">
                  {{dayItem.lable}}
                </el-checkbox>
              </el-checkbox-group>
              <div class="time-box">
                <div class="single-time" v-for="(timeSlotItem,timeSlotIndex) in item.timePoint"  :key="timeSlotIndex">
                  <el-time-picker
                          style="background:#fff"
                          is-range
                          v-model="timeSlotItem.time"
                          :clearable="false"
                          :editable="false"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          placeholder="选择时间范围">
                  </el-time-picker>
                  <i class="V7_iconfont V7_iconV7tubiao-109 delete-point" v-if="item.timePoint.length !== 1" @click="addOrDeleteTimeList(index, 'delete', timeSlotIndex)"></i>
                  <i class="V7_iconfont V7_iconV7tubiao_xinzeng-104 add-point" v-if="timeSlotIndex === item.timePoint.length - 1" @click="addOrDeleteTimeList(index, 'add', timeSlotIndex)"></i>
                </div>
              </div>
              <span class="iconfont delete-periods" v-show="form.cyclePeriods.length > 1" @click.stop="addOrDeleteTimeIntervalList(index, 'delete')"></span>
            </div>
            <span class="V7_iconfont V7_iconV7tubiao_xinzeng add-periods" v-if="index === form.cyclePeriods.length -1" @click.stop="addOrDeleteTimeIntervalList(index, 'add')">添加时段</span>
          </div>
        </el-form-item>
        <el-form-item label="时段" v-if="form.type === 'stable'">
          <div class="periods-box">
            <div v-for="(item, index) in form.stablePeriods" :key="index" class="periods-item">
              <el-date-picker
                      v-model="item.time"
                      type="datetimerange"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
              </el-date-picker>
              <i class="V7_iconfont V7_iconV7tubiao-109 delete-stable" v-if="form.stablePeriods.length !== 1"  @click="addOrDeleteStable(index, 'delete')"></i>
              <span class="V7_iconfont V7_iconV7tubiao_xinzeng-104 add-point" v-if="index === form.stablePeriods.length - 1"  @click.stop="addOrDeleteStable(index, 'add')"></span>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { IvrModule } from '@/store/modules/config/ivr'
import { deepClone, getFormatDateTime } from '@/utils/common'
import commonDrawer from '@/common/views/drawer/index.vue'

@Component({
  name: 'TimeDetial',
  components: { commonDrawer }
})
export default class TimeDetial extends Vue {
  [x: string]: any
  @Prop({ default: 'add' }) private type!: string
  private drawer: boolean = false // 抽屉的控制值
  private rules: object = { // 表单校验的规则
    name: [{ required: true, message: '必填', trigger: 'blur' }],
    drscription: [{ required: true, message: '必填', trigger: 'blur' }]
  }

  private form: any = { // 初始表单
    _id: '',
    name: '',
    description: '',
    type: 'cycle',
    cyclePeriods: [{ days: ['mon', 'tue', 'wed', 'thu', 'fri'], timePoint: [{ time: [new Date('2020-10-23 09:00:00'), new Date('2020-10-23 18:00:00')] }] }],
    stablePeriods: [{ time: [] }]
  }

  private restForm () { // 重置表单
    this.form = {
      id: '',
      name: '',
      description: '',
      type: 'cycle',
      cyclePeriods: [{ days: ['mon', 'tue', 'wed', 'thu', 'fri'], timePoint: [{ time: [new Date('2020-10-23 09:00:00'), new Date('2020-10-23 18:00:00')] }] }],
      stablePeriods: [{ time: [] }]
    }
  }

  private dayList: object[] = [ // 星期列表
    { lable: '周一', value: 'mon' },
    { lable: '周二', value: 'tue' },
    { lable: '周三', value: 'wed' },
    { lable: '周四', value: 'thu' },
    { lable: '周五', value: 'fri' },
    { lable: '周六', value: 'sat' },
    { lable: '周日', value: 'sun' }
  ]

  get currentDisabled () { // 当前时间段中可以选择的星期，其他为disabled
    const ruleArr = this.form.cyclePeriods
    const newArr = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
    return this.handleData(ruleArr, newArr) || []
  }

  private compareDate () { // 每个时间段的时间点是否重复
    let flag = true
    this.form.cyclePeriods.forEach((item2: any) => {
      let begin = [] as any []
      let end = [] as any []
      item2.timePoint.forEach((item3: any) => {
        begin.push(item3.time[0])
        end.push(item3.time[1])
      })
      begin = begin.sort()
      end = end.sort()
      for (let i = 1; i < begin.length; i++) {
        if (begin[i] <= end[i - 1]) {
          flag = false
          return false
        }
      }
    })
    return flag
  }

  private changeDays (indexChild: number, value: string[]): void { // 选择日期的时候，智能匹配，每个时间内的星期不能重复，控制disabled
    if (value.length === 0 && indexChild !== 0) {
      (this as any).$message.error('无法取消，操作错误，已为您智能选择！')
      const timeSlots = this.form.cyclePeriods
      const arr = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
      timeSlots.forEach((item: any) => {
        item.days.forEach((item2: any) => {
          arr.splice(arr.indexOf(item2), 1)
        })
      })
      this.form.cyclePeriods[indexChild].days = arr || []
    }
  }

  private handleData (cyclePeriods: any, newArr: string[]) { // 处理数据（"周*"是否可选）
    cyclePeriods.forEach((item: any) => {
      item.days.forEach((item1: string) => {
        newArr.splice(newArr.indexOf(item1), 1)
      })
    })
    return newArr
  }

  private addOrDeleteTimeList (indexChild: number, type: string, timeSlotIndex: number) { // 添加或删除时间点
    const timeSlotLength = this.form.cyclePeriods[indexChild].timePoint
    if ((type === 'add' && timeSlotLength >= 12) || (type === 'delete' && timeSlotLength <= 1)) {
      (this as any).$message.error('单个时间段内的时间配置条数不能小于1也不能大于12！')
      return false
    }
    if (type === 'add') {
      this.form.cyclePeriods[indexChild].timePoint.push({ time: [new Date('2020-10-23 09:00:00'), new Date('2020-10-23 18:00:00')] })
    } else {
      this.form.cyclePeriods[indexChild].timePoint.splice(timeSlotIndex, 1)
    }
  }

  private addOrDeleteStable (indexChild: number, type: string) { // 添加或者删除时间段（固定时间）
    const self = (this as any)
    if (type === 'add') {
      this.form.stablePeriods.push({ time: [] })
    } else {
      self.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.$message({ type: 'success', message: '删除成功!' })
        this.form.stablePeriods.splice(indexChild, 1)
      }).catch(() => {
        // self.$message({ type: 'info', message: '已取消删除' })
      })
    }
  }

  private addOrDeleteTimeIntervalList (indexChild: number, type: string) { // 添加或删除时间段
    const intervalLength = this.form.cyclePeriods.length
    const self = (this as any)
    if ((type === 'add' && intervalLength >= 12) || (type === 'delete' && intervalLength <= 1)) {
      self.$message.error('单个时间段内的时间配置条数不能小于1也不能大于12！')
      return false
    }
    if (type === 'add') {
      const preInterval = this.form.cyclePeriods
      if (preInterval[indexChild] && preInterval[indexChild].days) {
        const arr = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
        let flag = false
        for (let i = 0; i < preInterval.length; i++) {
          if (preInterval[i].days.length === 0) {
            flag = true
          }
          preInterval[i].days.forEach((item: string) => {
            arr.splice(arr.indexOf(item), 1)
          })
        }
        if (flag) {
          self.$message.error('请先选择该时间段内的星期')
          return false
        }
        if (arr.length === 0) {
          self.$message.error('周一到周日已选，不可再添加时间段！')
          return false
        }
        this.form.cyclePeriods.push({ days: arr || [], timePoint: [{ time: [new Date('2020-10-23 09:00:00'), new Date('2020-10-23 18:00:00')] }] })
      }
    } else {
      self.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.$message({ type: 'success', message: '删除成功!' })
        this.form.cyclePeriods.splice(indexChild, 1)
      }).catch(() => {
        // self.$message({ type: 'info', message: '已取消删除' })
      })
    }
  }

  private openOrCloseDrawer (data: any) { // 打开或者是关闭抽屉 || 父级调用
    this.drawer = !this.drawer
    this.$nextTick(() => {
      (this as any).$refs.formRef.clearValidate()
    })
    if (data) { // 编辑
      this.form = this.handleForm(data)
    } else { // 新增
      this.restForm()
    }
  }

  private handleForm (data: any) { // 编辑的时候，要把后台的返回的数据整理成初始化表单的形式
    if (typeof data !== 'object') {
      return {}
    }
    const handleData = deepClone(data)
    handleData.cyclePeriods.forEach((item: any) => {
      item.timePoint.forEach((item1: any) => {
        if (item1.start) {
          item1.time = [new Date('2020-10-23 ' + item1.start), new Date('2020-10-23 ' + item1.end)]
          delete item1.start
          delete item1.end
        } else {
          item1.time = [new Date('2020-10-23 09:00:00'), new Date('2020-10-23 18:00:00')]
        }
      })
    })
    if (handleData.stablePeriods.length > 0) {
      handleData.stablePeriods.forEach((item: any) => {
        if (item.start) {
          item.time = [new Date(item.start), new Date(item.end)]
          delete item.start
          delete item.end
        } else {
          item.time = []
        }
      })
    } else { // 从周期时间改成固定时间，从无到有
      handleData.stablePeriods = [{ time: [] }]
    }

    return handleData
  }

  private beforeSave () { // 保存时间条件之前，做表单校验和数据格式整理
    const actionData = deepClone(this.form)
    if (!this.compareDate()) {
      (this as any).$message.error('每个时间段的时间点不能重合！')
      return 'no'
    }
    actionData.cyclePeriods.forEach((item: any) => {
      const newArr = [] as any []
      item.timePoint.forEach((item1: any) => {
        if (item1.time && item1.time[0] && item1.time[1]) {
          newArr.push({ start: getFormatDateTime(item1.time[0], 'noYear'), end: getFormatDateTime(item1.time[1], 'noYear') })
        }
      })
      item.timePoint = newArr
    })
    const newArr2 = [] as any []
    let flag = false
    actionData.stablePeriods.forEach((item: any) => {
      if (item.time && item.time[0] && item.time[1]) {
        newArr2.push({ start: getFormatDateTime(item.time[0], ''), end: getFormatDateTime(item.time[1], '') })
      } else {
        flag = true
      }
    })
    if (actionData.type === 'stable' && flag) {
      (this as any).$message.error('时间段不能为空')
      return 'no'
    }
    actionData.stablePeriods = newArr2
    return actionData
  }

  private save () { // 保存
    (this as any).$refs.formRef.validate((valid: boolean) => {
      if (valid) {
        const actionData = this.beforeSave() // 保存时间条件之前，做表单校验和数据格式整理
        if (actionData === 'no') {
          return false
        }
        const actionUrl = this.type === 'add' ? '/base/action/config/timecondition/create' : '/base/action/config/timecondition/update'
        const data = { url: actionUrl, method: 'POST', data: actionData }
        IvrModule.IvrCommonAction(data).then((res: any) => {
          if (res && res.success) {
            this.$emit('refresh', this.type === 'add' ? 'addSuccess' : null)
            this.drawer = false
            this.$message({ message: '保存成功', type: 'success' })
            if (this.type === 'add') {
              this.$addOneCache('timeConditionList', res.data, false)
            } else {
              this.$updateCache('timeConditionList', res.data, '_id', false)
            }
          }
        })
      } else {
        return false
      }
    })
  }

  private handleClose () { // 关闭抽屉
    this.drawer = false
  }
}
</script>
<style lang="stylus" scoped>
.time-step-box
   .dashed-box
      position relative
      overflow hidden
      background $bgc-gray
      padding 20px
      margin-bottom 20px
      border-radius 4px
     .single-time
       margin-bottom 20px
       &:last-child
         margin-bottom 0
       &:first-child
         margin-top 10px
  .add-periods,.add-point
    font-size 12px
    color $c-main
    cursor pointer
  .add-periods
    position absolute
    bottom -20px
    font-weight 500
    &:before
      margin-right 4px
  .add-point
    font-size 16px
    margin-left 10px
  .delete-point, .delete-stable
    color $icon-gray
    cursor pointer
    margin-left 10px
    &:hover
     color $c-danger
  .delete-periods
    position absolute
    top -18px
    right -18px
    background $c-danger
    color #fff
    width 36px
    height 36px
    display block
    text-align center
    border-radius 50%
    cursor pointer
    &:before
     content 'x'
     position absolute
     top 10px
     right 7px
     font-size 14px
     font-weight bold
     width 36px
     height 36px
.periods-box
  background $bgc-gray
  padding 20px
  margin-bottom 20px
  border-radius 4px
  .periods-item
    margin-bottom 20px
    &:last-child
      margin-bottom 0
    &:first-child
      margin-top 10px
</style>
